package com.ktjiaoyu.crm.config.shiro;

import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.RoleService;
import com.ktjiaoyu.crm.service.UserService;
import com.ktjiaoyu.crm.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.Set;

/**
 * 自定义Realm
 */
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private UserService userService;

    @Autowired
    private RightService rightService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisUtils redisUtils;

    //Redis中缓存数据的key前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count:"; //登录次数计数
    private String SHIRO_IS_LOCK = "shirl_is_lock:";         //锁定用户登录

    /**
     * 认证方法
     * @param authenticationToken 用户输入的用户名与密码
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("调用doGetAuthenticationInfo()进行用户认证................");
        //获取用户身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //每次访问，登录次数+1
        redisUtils.incr(SHIRO_LOGIN_COUNT+token.getUsername(),1);
        //计数大于 5 时，设置用户被锁定一小时，清空登录计数
        if(Integer.parseInt(redisUtils.get(SHIRO_LOGIN_COUNT+token.getUsername()).toString())>5){
            redisUtils.set(SHIRO_IS_LOCK+token.getUsername(),"LOCK");
            //锁定用户一小时，设置Redis过期时间，单位S
            redisUtils.expire(SHIRO_IS_LOCK+token.getUsername(),3600);
            //清空登录计数
            redisUtils.del(SHIRO_LOGIN_COUNT+token.getUsername());
        }
        //判断用户是否锁定
        if("LOCK".equals(redisUtils.get(SHIRO_IS_LOCK+token.getUsername()))) throw new DisabledAccountException();
        //拿到用户名去数据库查询用户信息
        User user = userService.getUesrByName(token.getUsername());
        //判断用户名是否存在
        if(user == null) throw new UnknownAccountException();   //用户不存在
        if(user.getUsrFlag()==null || user.getUsrFlag().intValue()==0) throw new LockedAccountException();  //用户被锁定
        //principal：身份
        //credentials：凭证
        //realmName：当前Realm的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUsrPassword(), ByteSource.Util.bytes("czkt"),getName());
        log.info("调用doGetAuthenticationInfo()用户认证结束................");
        return info;
    }


    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取权限信息
        User user = (User)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //动态授权
        //info.addRole(user.getRole().getRoleName());
        //根据用户ID查询角色信息
        Role role = roleService.findRoleByUserId(user.getUsrId());
        if(role!=null) info.addRole(role.getRoleName());
        //从数据库中查询该角色所拥有的权限
        Set<String> rights =  rightService.findRightsByRoleId(role.getRoleId());
        //给Subject授权
        info.addStringPermissions(rights);
        return info;
    }

    /**
     * 清空当前认证用户权限缓存
     */
    public void clearMyCachedAuthorizationInfo() {
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

    /**
     * 清空所有用户权限缓存
     */
    public void clearAllCachedAuthorizationInfo() {
        if (this.isAuthorizationCachingEnabled()) { // 权限缓存是否可用
            Cache<Object, AuthorizationInfo> cache = null;
            CacheManager cacheManager = this.getCacheManager();
            if (cacheManager != null) {
                String cacheName = this.getAuthorizationCacheName(); // 获得权限缓存名称
                cache = cacheManager.getCache(cacheName); // 获得权限缓存
            }
            if (cache != null) {
                cache.clear(); // 清空
            }
        }
    }


}
